﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.IO;

namespace MVVMComun
{
   public  class FlickerService:ServiceModel
    {
        public event EventHandler<FlickerResponseEventArgs> FlickerServiceResponseReady;

        private string size;

        public string Size
        {
            get { return size; }
            set { size = value; }
        }
         
       public FlickerService() {
           Size = "b";
        }


        public async void  getFotos(string query) {

            serviceUri = new Uri("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=2ea68f4c4c14b8aabaf2cd700c18dc86&per_page=10&text=" + query + "&format=rest");
            HttpClient hc = new HttpClient();
            var result = await hc.GetStringAsync(serviceUri);
           

            XDocument doc = XDocument.Parse(result);

            var rr = (from ph in doc.Descendants("photo")
                      select new
                      {
                          title = ph.Attribute("title").Value,
                          id = ph.Attribute("id").Value,
                          farm = ph.Attribute("farm").Value,
                          server = ph.Attribute("server").Value,
                          secret = ph.Attribute("secret").Value
                      }).ToList();

            List<Foto> listaResult=new List<Foto>(); 
            foreach (var item in rr)
            {
                Foto ins = new Foto() { Id= item.id, Titulo = item.title, Url = string.Format("http://farm{0}.staticflickr.com/{1}/{2}_{3}_" + Size + ".jpg", item.farm, item.server, item.id, item.secret) };

                listaResult.Add(ins);
            }

            if (FlickerServiceResponseReady != null)
                FlickerServiceResponseReady(this, new FlickerResponseEventArgs(listaResult));
         


        }
    }
}
